package com.portal.framework.exception.handler.interceptor;

import java.lang.reflect.Method;
import java.text.MessageFormat;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.portal.framework.util.ValueUtil;

/**
 * ajax的异常处理拦截器<BR>
 * 如果在ajax调用中出现异常,则用返回异常的信息(在信息前加 "exception:" 字符串 )
 * 
 * @author 卢烁波
 * @date 2007-3-10
 */
public class AjaxExceptionHandleInterceptor implements MethodInterceptor {
	private static final Log log = LogFactory
			.getLog(AjaxExceptionHandleInterceptor.class);

	public static final String EXCEPTION_PREFIX = "exception:";

	public Object invoke(MethodInvocation inv) throws Throwable {
		Method mtd = inv.getMethod();
		if (log.isDebugEnabled()) {
			String msg = "进入ajax异常处理拦截器.类名=[{0}],方法名=[{1}]";
			log.debug(MessageFormat.format(msg, inv.getThis().getClass()
					.getName(), mtd.getName()));
		}
		Object ret = null;
		try {
			ret = inv.proceed();
		} catch (Throwable e) {
			String msg = null;
			if (e.getCause() != null) {
				msg = e.getCause().getMessage();
			}
			if (msg == null) {
				msg = e.getMessage();
			}

			String retStr = EXCEPTION_PREFIX + msg;
			if (log.isDebugEnabled()) {
				Class<? extends Throwable> eclass = e.getClass();
				log.debug("在ajax异常拦截器中catch到异常.异常为: " + eclass.getName());
				log.debug(MessageFormat.format("异常为:[{0}],message为:[{1}] ",
						eclass.getName(), msg));

				log.debug("返回信息为 : " + retStr);
				log.error("异常信息 : ", e);
			}

			/**
			 * 如果返回的类型为字符串
			 */
			if (mtd.getReturnType().isAssignableFrom(String.class)) {
				return retStr;
			} else {
				if (log.isWarnEnabled()) {
					String fmsg = "抓到异常,返回类型为[{0}],返回类型不是字符串,将返回null!";
					log.warn(MessageFormat.format(fmsg, mtd.getReturnType()
							.getName(), e));
				}

				/**
				 * 如果不为字符串类型,则返回默认的值
				 */
				return ValueUtil.getDefaultValue(mtd.getReturnType());
			}
		}
		if (log.isDebugEnabled()) {
			String msg = "退出ajax异常处理拦截器.类名=[{0}],方法名=[{1}]";
			log.debug(MessageFormat.format(msg, inv.getThis().getClass()
					.getName(), inv.getMethod().getName()));
		}

		return ret;
	}

}
